<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/1/29
 * Time: 16:28
 */
declare(strict_types=1);
namespace App\Controller\MchApi;
use App\Exception\XZXValidationException;
use App\Middleware\MchApi\MchJWTAuthMiddleware;
use App\Service\MchTradeWebsiteService;
use App\Utils\CustomUtils;
use App\Utils\DateUtils;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use Hyperf\Contract\TranslatorInterface;

/**
 * Class MchTradeWebsiteController
 * @package App\Controller
 * @Controller(prefix="/mch/api/mchTradeWebsite")
 */
class MchTradeWebsiteController extends MchBaseController
{

    /**
     * @Inject
     * @var TranslatorInterface
     */
    private $translator;

    /**
     * @Inject()
     * @var ValidatorFactoryInterface
     */
    protected $validationFactory;

    /**
     * @Inject()
     * @var MchTradeWebsiteService
     */
    protected $MchTradeWebsiteService;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;

    public function __construct(LoggerFactory $loggerFactory)
    {
        // 第一个参数对应日志的 name, 第二个参数对应 config/autoload/logger.php 内的 key
        $this->logger = $loggerFactory->get('log', 'default');
    }

    private function setLocale()
    {
        if($this->request->header('locale') == 'en')
        {
            $this->translator->setLocale('en');
        }
    }

    /**
     * 查看
     * @PostMapping(path = "get")
     * @Middleware(MchJWTAuthMiddleware::class)
     */
    public function get(RequestInterface $request)
    {
        $this->setlocale();
        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'id' => 'required|uuid',
            ]
        );

        if ($validator->fails()){
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        $param['mchId'] = $ext['mchId'];    
        $param['source'] = 1;    
        return $this->MchTradeWebsiteService->get($param);
    }

    /**
     * 编辑
     * @PostMapping(path = "edit")
     * @Middleware(MchJWTAuthMiddleware::class)
     */
    public function edit(RequestInterface $request)
    {
        $this->setlocale();
        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'id'    => 'required|uuid',
                'url'   => 'required',
            ]
        );

        if ($validator->fails()){
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        $param['source'] = 1;
        $param['createBy']  =  $ext['createBy'];
        $param['mchId']     =  $ext['mchId'];
        $param['mchNo']     =  $ext['mchNo'];
        return $this->MchTradeWebsiteService->edit($param);
    }

    /**
     * 删除
     * @PostMapping(path = "del")
     * @Middleware(MchJWTAuthMiddleware::class)
     */
    public function del(RequestInterface $request)
    {
        $this->setlocale();
        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'id' => 'required|uuid',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        $param['source'] = 1;
        $param['mchId']     =  $ext['mchId'];
        $param['mchNo']     =  $ext['mchNo'];
        return $this->MchTradeWebsiteService->del($param);
    }

    /**
     * 添加
     * @PostMapping(path = "add")
     * @Middleware(MchJWTAuthMiddleware::class)
     */
    public function add(RequestInterface $request)
    {
        $this->setlocale();
        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'url'   => 'required',
            ]
        );

        if ($validator->fails()){
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        $param['source'] = 1;
        $param['createBy'] =  $ext['createBy'];
        $param['mchId']     =  $ext['mchId'];
        $param['mchNo']     =  $ext['mchNo'];
        return $this->MchTradeWebsiteService->add($param);
    }

    /**
     * 查询
     * @PostMapping(path = "list")
     * @Middleware(MchJWTAuthMiddleware::class)
     */
    public function list(RequestInterface $request)
    {
        $this->setlocale();
        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'page'              => 'required|integer|min:1',
                'limit'             => 'required|integer|min:1',
                'search.mchNo'      => 'sometimes|required',
            ]
        );

        if ($validator->fails()){
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        $param['uid']      =  $ext['uid'];
        isset($ext['mchId']) && $param['mchId'] = trim($ext['mchId']); 

        if(isset($param['search'])){
            $search = $param['search'];
            $param['search']['mchNo'] = $ext['mchNo'];
            CustomUtils::xzxAddSearch($param, $search, 'url');
            CustomUtils::xzxAddSearch($param, $search, 'createTimeRange');
            if(isset($param["createTimeRange"]))
            {
                try {
                    $param['createTimeRange'][0] = DateUtils::dateToTimeStamp($param['createTimeRange'][0]);
                    $param['createTimeRange'][1] = DateUtils::dateToTimeStamp($param['createTimeRange'][1]);
                } catch (\Throwable $th) {
                    unset($param['createTimeRange']);
                }
            }
    
        }

        return $this->MchTradeWebsiteService->list($param);
    }

}